package com.gitee.cui.netty.basic;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 使用netty实现的消息discard功能
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/20 16:14
 **/
public class NettyDiscardServer {

    private int serverPort;

    private ServerBootstrap bootstrap = new ServerBootstrap();

    public NettyDiscardServer(int port) {
        serverPort = port;
    }

    public void runServer() {
        // 创建反应器轮询组
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            // 1.设置启动器轮询组
            bootstrap.group(boss, worker);
            // 2.设置nio类型的通道
            bootstrap.channel(NioServerSocketChannel.class);
            // 3.设置监听端口
            bootstrap.localAddress(serverPort);
            // 4.设置通道的参数
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            // 5.装配子通道流水线
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                // 有连接到达时，会创建一个通道
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 流水线的职责，负责管理通道中的处理器
                    // 向“子通道”（传输通道）流水线添加一个处理器
                    socketChannel.pipeline().addLast(new NettyDiscardHandler());
                }
            });
            // 6.开始绑定服务器
            // 通过调用sync同步方法阻塞直到绑定成功
            ChannelFuture channelFuture = bootstrap.bind().sync();
            Logger.info("服务器启动成功，监听端口：" + channelFuture.channel().localAddress());
            // 7.等待通道关闭的异步任务结束
            // 服务监听通道会一直等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 8.优雅的关闭EventLoopGroup
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new NettyDiscardServer(NettyDemoConfig.SOCKET_SERVER_PORT).runServer();
    }
}
